package com.itheima.service;

import com.itheima.pojo.User;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class SecurityUserService implements UserDetailsService {

    //模拟数据库
    public static Map<String, User> map = new HashMap<>();
    static {
        User user1 = new User();
        user1.setUsername("zhangsan");
        user1.setPassword("123456");

        User user2 = new User();
        user2.setUsername("lisi");
        user2.setPassword("456789");

        map.put(user1.getUsername(),user1);
        map.put(user2.getUsername(),user2);
    }
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        System.out.println("用户名为："+username);
        //根据用户名查询用户信息
        User user = map.get(username);
        if (user!=null){
            //框架进行密码比对
            //用户名存在
            //数据库中密码（模拟）
            String password = user.getPassword();
            //设置用户角色和权限(模拟从数据库中获取)
            List<GrantedAuthority> list = new ArrayList<>();

            if (username.equals("zhangsan")){
                list.add(new SimpleGrantedAuthority("ROLE_ADMIN"));//以ROLE_开头的都是角色，其他的为权限
            }
            list.add(new SimpleGrantedAuthority("pre_a"));
            list.add(new SimpleGrantedAuthority("pre_b"));
            org.springframework.security.core.userdetails.User securityUser = new org.springframework.security.core.userdetails.User(username,"{noop}"+password,list);
            return securityUser;
        }else {
            return null;
        }

    }
}
